#pragma once

#include "../3rd/cpp-httplib/httplib.h"
#include "../3rd/rapidjson/include/rapidjson/document.h"
#include "utils/dbutils.hpp"
#include "utils/kvutils.hpp"
#include "utils/transutils.hpp"

using namespace httplib;
using namespace rapidjson;

class Warehouse_ {
 public:
  std::string suppliesName;    // 物资名称
  std::string type;            // 物资种类
  std::string specifications;  // 规格
  std::string units;           // 单位
  std::string number;          // 数量

  template <typename Writer>
  void Serialize(Writer &writer) const {
    writer.StartObject();
    writer.String("suppliesName");
    writer.String(suppliesName.c_str());
    writer.String("type");
    writer.String(type.c_str());
    writer.String("specifications");
    writer.String(specifications.c_str());
    writer.String("units");
    writer.String(units.c_str());
    writer.String("number");
    writer.String(number.c_str());
    writer.EndObject();
  }
};

void Warehouse(const Request &req, Response &res) {
  res.set_header("Access-Control-Allow-Origin", "*");
  auto result = KVWrapper::GetInstance("warehouse")->GetAll();
  std::string json;
  bool first = true;
  json += "[";
  for (const auto &supply : (*result)) {
    auto attrs = Split(supply.first);
    if (!first) {
      json += ", ";
    }
    Warehouse_ warehouse{attrs[0], attrs[1], attrs[2], attrs[3], supply.second};
    json += Object2Json(warehouse);
    first = false;
  }
  json += "]";
  res.set_content(json, "application/json");
}

void WarehouseNumber(const Request &req, Response &res) {
  res.set_header("Access-Control-Allow-Origin", "*");
  auto result =
      KVWrapper::GetInstance("warehouse")
          ->PrefixGet(Concatenate({req.get_param_value("suppliesName"),
                                   req.get_param_value("specifications")}));
  res.set_content("{\"number\": " + result->at(0).second + "}", "application/json");
}